package qj.util.collection;

import qj.util.Cols;
import qj.util.ReflectUtil;
import qj.util.funct.F0;
import qj.util.funct.Fs;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

public class MultiColLooper<A> implements Iterator<A> {
    private List<List<A>> lists;
    private List<AtomicInteger> indexes = new ArrayList<AtomicInteger>();
    private int pointAt = 0;

    public MultiColLooper(List<List<A>> lists) {
        this.lists = lists;
        indexes = Cols.createList(lists.size(), Fs.construct(AtomicInteger.class) );
    }

    public boolean hasNext() {
        for (int i = 0; i < indexes.size(); i++) {
            AtomicInteger index =  indexes.get(i);
            if (index.get() < lists.get(i).size()) {
                return true;
            }
        }
        return false;
    }

    @SuppressWarnings({"unchecked"})
    public A next() {
        pointAt = -1;
        A comparer = null;
        for (int i = 0; i < indexes.size(); i++) {
            AtomicInteger index =  indexes.get(i);
            List<A> list = lists.get(i);
            A elem = list.get(index.get());
            if (comparer == null) {
                pointAt = i;
                comparer = elem;
            } else {
                if (((Comparable<A>)comparer).compareTo(elem) > 0) {
                    pointAt = i;
                    comparer = elem;
                } else {
//                    continue;
                }
            }
        }
        return comparer;
    }

    public void remove() {
        lists.get(pointAt).remove(indexes.get(pointAt).get());
    }
}
